import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  position: {lng: 0,lat: 0},
  signTime: 0,
  signAuto: 0,
  studentId: '',
  wind: {signWid:'', signInstanceWid: ''},
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_POSITION: (state, position)=>{
    state.position.lng = position.split(',')[0]
    state.position.lat = position.split(',')[1]
    console.log("全局坐标位置设置成功")
  },
  SET_SIGNTIME: (state, signTime)=>{
    state.signTime = signTime
  },
  SET_SIGNAUTO: (state, signAuto)=>{
    state.signAuto = signAuto
  },
  SET_STUDENTID: (state, studentId)=>{
    state.studentId = studentId
  },
  SET_WIND: (state, wind) => {
    state.wind.signWid = wind.signWid
    state.wind.signInstanceWid = wind.signInstanceWid
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ studentId: username.trim(), studentPass: password }).then(data => {
        console.log(data);
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 设置用户头像
  setImg({ commit },img){
    commit('SET_AVATAR',img);
  },

  //任务{signWid: "1048675", signInstanceWid: "46562"}
  setWind({ commit },wind){
    commit('SET_WIND',wind);
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(data => {
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name ,img } = data

        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        // "https://z3.ax1x.com/2021/08/17/f4T1Vs.png"

        commit('SET_ROLES', [roles])
        commit('SET_NAME', name)
        commit('SET_AVATAR', img)
        commit('SET_POSITION', data.user.signLongitudeLatitude)
        commit('SET_SIGNTIME', data.user.signTime)
        commit('SET_SIGNAUTO', data.user.signAuto)
        commit('SET_STUDENTID', data.user.studentId)
        resolve(data)
      }).catch(error => {

        reject(error)
      })
      
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
